<template>
  <v-page
    v-model="refreshing"
    background="#f5f6fa"
    header-background="white"
    footer-background="white"
    padding-top="24rpx"
    :loading="loading"
    :footer="status !== '已撤回' && status !== '已关闭'"
    @refresh="refreshHandle"
  >
    <template #header>
      <v-navbar title="投诉详情" native />
    </template>
    <template #default>
      <view class="dialog-list">
        <view v-if="status === '已处理'" class="feedback-container">
          <view class="main">
            <v-icon
              size="36rpx"
              src="@/static/icons/complaint-details-clock.svg"
            />
            <view class="main-text">
              商家已处理，待您反馈
            </view>
          </view>
          <view class="sub">
            <text>还剩</text>
            <text class="countdown">
              <wd-count-down
                v-if="countDown"
                :time="countDown"
                :format="countDownformate"
              />
            </text>
            <text>完成处理</text>
          </view>
          <v-button
            type="primary"
            :custom-style="{ height: '80rpx', width: '168rpx' }"
            @click="isShowFeedback = true"
          >
            立即反馈
          </v-button>
        </view>
        <view v-else-if="status === '已撤回'" class="feedback-container">
          <view class="main">
            <v-icon
              size="36rpx"
              src="@/static/icons/complaint-details-alert.svg"
            />
            <view class="main-text">
              投诉已撤回
            </view>
          </view>
          <view class="sub">
            <text>如仍未解决您的问题，可</text>
            <text class="complaint-button" @click="redirectToComplaint">
              再次投诉
            </text>
          </view>
        </view>
        <view v-else-if="status === '已关闭'" class="feedback-container">
          <view class="main">
            <v-icon
              size="36rpx"
              src="@/static/icons/complaint-details-alert.svg"
            />
            <view class="main-text">
              投诉已关闭
            </view>
          </view>
          <view class="sub">
            <text>如仍未解决您的问题，可</text>
            <text class="complaint-button" @click="redirectToComplaint">
              再次投诉
            </text>
          </view>
        </view>
        <complaint-order-item
          v-else-if="order && product"
          :order="order"
          :product="product"
          :complaint="complaint"
          :info="complaintInfo"
        />
        <template v-for="(log, index) in logs" :key="index">
          <view v-if="log.time" class="time">
            {{ log.time }}
          </view>
          <view
            class="dialog-item"
            :class="{
              user: log.type === 'CUSTOMER',
              merchant: log.type === 'MERCHANT'
            }"
          >
            <view v-if="log.type === 'MERCHANT'" class="merchant-avatar">
              商
            </view>
            <view class="dialog-block" :class="{ 'width-fix': log.widthFix }">
              <view
                v-for="(item, itemIndex) in log.contents"
                :key="itemIndex"
                class="dialog-block-item"
              >
                <view v-if="item.label" class="label">
                  {{ item.label }}
                </view>
                <view v-if="item.content" class="content">
                  {{ item.content }}
                </view>
                <view v-if="item.images?.length" class="image-list">
                  <v-image
                    v-for="(image, imageIndex) in item.images"
                    :key="imageIndex"
                    width="150rpx"
                    height="150rpx"
                    border-radius="16rpx"
                    :src="image"
                    preview
                    mode="aspectFill"
                  />
                </view>
              </view>
            </view>
            <view v-if="log.type === 'CUSTOMER'" class="user-avatar">
              买
            </view>
          </view>
        </template>
      </view>
    </template>
    <template #footer>
      <view class="details-footer">
        <template v-if="status === '已完成'">
          <view class="finished-button">
            <v-icon
              size="36rpx"
              src="@/static/icons/complaint-details-check.svg"
            />
            <view class="finished-button-text">
              已处理完成
            </view>
          </view>
        </template>
        <template v-else>
          <v-button
            type="plain"
            :custom-style="{ width: '168rpx' }"
            @click="cancelHandle"
          >
            撤销投诉
          </v-button>
          <v-button
            type="primary"
            :custom-style="{ width: '510rpx' }"
            :disabled="status !== '待处理' && status !== '已回复'"
            @click="isShowMessage = true"
          >
            留言
          </v-button>
        </template>
      </view>
    </template>
    <template #popup>
      <complaint-message-popup
        :id="complaintId"
        v-model:show="isShowMessage"
        @refresh="getDetails"
      />
      <wd-popup
        v-model="isShowFeedback"
        :close-on-click-modal="false"
        custom-style="background: transparent"
      >
        <view class="popper-container">
          <view class="popper-title">
            是否认可投诉处理结果
          </view>
          <view class="popper-content">
            如未解决问题，您可以选择不认可 从新申请投诉
          </view>
          <view class="popper-button-list">
            <v-button
              type="plain"
              :custom-style="{ height: '80rpx', width: '240rpx' }"
              @click="handleFeedback(false)"
            >
              不认可
            </v-button>
            <v-button
              type="primary"
              :custom-style="{ height: '80rpx', width: '240rpx' }"
              @click="handleFeedback(true)"
            >
              认可
            </v-button>
          </view>
        </view>
      </wd-popup>
    </template>
  </v-page>
</template>

<script setup lang="ts">
import ComplaintOrderItem from './modules/complaint-order-item.vue';
import ComplaintMessagePopup from './modules/complaint-message-popup.vue';
import { formateDateTime } from '@/utils/formater';

const loading = ref(true);
const complaintId = ref('');
const complaint = ref<OrderComplaintDetailVO>();
const status = computed(() => {
  if (!complaint.value) return '';
  switch (true) {
    case complaint.value.status === 'PENDING':
      return '待处理';
    case complaint.value.status === 'PROCESSING':
      return '已回复';
    case complaint.value.status === 'PROCESSED':
      return '已处理';
    case complaint.value.status === 'CLOSE':
    case complaint.value.status === 'CLOSE_CUSTOMER_TIMEOUT':
    case complaint.value.status === 'FINISH' && !complaint.value.accept_flag:
      return '已关闭';
    case complaint.value.status === 'FINISH':
      return '已完成';
    case complaint.value.status === 'REVOCATION':
      return '已撤回';
    default:
      return '';
  }
});
const reasons = {
  UNSHIPPED: '超时未发货',
  LESS_SHIPPED: '少发货',
  WRONG_SHIPPED: '错发货',
  SHAM_SHIPPED: '虚假发货',
  DISCREPANCY_DESCRIPTION: '描述不符',
  DAMAGED: '商品破损',
  QUALITY_PROBLEM: '质量问题',
  CUSTOMER_SERVICE_NOT_REPLY: '客服不回复',
  CUSTOMER_SERVICE_NOT_PROCESS: '客服不处理',
  ABNORMAL_ATTITUDE: '态度异常',
  MINI_PROGRAM_EXPERIENCE: '小程序体验',
  ALIPAY_REPORT: '支付宝举报'
};
const complaintInfo = computed(() => {
  if (!complaint.value) return;
  if (!reasons[complaint.value.reason]) return;
  return `投诉：${reasons[complaint.value.reason]}`;
});
const getDetails = async () => {
  const response = await $api.getOrderComplaintDetailId(complaintId.value);
  switch (response.__error) {
    case undefined:
      complaint.value = response.data;
      refreshCountdown();
      break;
  }
};
const logs = computed(() => {
  if (!complaint.value) return [];
  const list: {
    type: 'CUSTOMER' | 'MERCHANT';
    contents: { label: string; content?: string; images?: string[] }[];
    widthFix?: boolean;
    time: string;
  }[] = [];
  const user = {
    type: 'CUSTOMER',
    contents: [
      {
        label: '投诉类型',
        content: {
          DELIVERY: '发货问题',
          PRODUCT: '商品问题',
          CUSTOMER_SERVICE: '客服问题',
          OTHER: '其它问题'
        }[complaint.value.problem_type]
      },
      { label: '投诉原因', content: reasons[complaint.value.reason] ?? '' },
      { label: '联系电话', content: complaint.value.mobile },
      { label: '问题描述', content: complaint.value.content },
      { label: '申请凭证', images: complaint.value.image ?? [] }
    ],
    time: formateDateTime(complaint.value.create_time) ?? '',
    widthFix: true
  } as (typeof list)[number];
  const merchant = {
    type: 'MERCHANT',
    contents: [
      {
        label: '沟通结果',
        content: complaint.value.compromise_flag ? '同意和解' : '拒绝和解'
      },
      {
        label: '处理方案',
        content: {
          REFUND: '仅退款',
          SALE_RETURN: '退货退款',
          CONSENSUS: '协商一致'
        }[complaint.value.process_scheme]
      },
      { label: '沟通说明', content: complaint.value.consult_content }
    ],
    time: formateDateTime(complaint.value.consult_time) ?? '',
    widthFix: true
  } as (typeof list)[number];
  list.push(user);
  if (complaint.value.consult_time) list.push(merchant);
  list.push(
    ...complaint.value.communicate_list.map((item) => {
      const contents: { label: string; content?: string; images?: string[] }[] =
        [];
      contents.push({ label: '', content: item.content });
      if (item.image?.length) contents.push({ label: '', images: item.image });
      return {
        type: item.type,
        contents,
        time: formateDateTime(item.createTime) ?? ''
      };
    })
  );
  list.sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
  if (complaint.value.status === 'REVOCATION') {
    list.push({
      type: 'CUSTOMER',
      contents: [{ label: '', content: '买家 撤销了投诉申请，投诉单已撤回' }],
      time: ''
    });
  } else if (complaint.value.status === 'CLOSE') {
    const lines = ['商家超时未处理，已自动退款'];
    const refunList = complaint.value.back_refund_view_list.filter(
      (item) => item.basic_status === 'SUCCESS'
    );
    if (refunList.length) {
      lines.push('');
      lines.push('该订单存在历史售后退款：');
      for (let i = 0; i < refunList.length; i += 1) {
        const item = refunList[i];
        lines.push(`售后退款：${item.apply_amount} 元`);
        lines.push(`退款流水: ${complaint.value.out_trade_no}`);
      }
      lines.push('');
    }
    if (complaint.value.overtime_refund_amount > 0) {
      lines.push(
        `投诉超时处理退款：${complaint.value.overtime_refund_amount} 元`
      );
      lines.push(`退款流水: ${complaint.value.out_trade_no}`);
    }
    list.push({
      type: 'MERCHANT',
      contents: [{ label: '', content: lines.join('\n') }],
      time: ''
    });
  }
  return list;
});

const order = ref<OrderVO>();
const product = computed(() => {
  if (!complaint.value || !order.value) return;
  const detailId = complaint.value.order_detail_id;
  return order.value.order_detail_list.find((item) => item.id === detailId);
});
const getOrderDetails = async () => {
  if (!complaint.value?.order_id) return;
  if (order.value) return;
  const response = await $api.getOrderQueryIdDetail(complaint.value.order_id);
  switch (response.__error) {
    case undefined:
      order.value = response.data;
      break;
  }
};

const countDown = ref(0);
const countDownformate = ref('DD天 HH:mm:ss');
const refreshCountdown = () => {
  if (!complaint.value) return;
  const num = parseFloat(complaint.value?.surplus_second ?? '');
  if (isNaN(num)) return;
  if (num <= 0) return;
  countDown.value = num * 1000;
  if (countDown.value > 24 * 60 * 60 * 1000) {
    countDownformate.value = 'DD天 HH:mm:ss';
  } else {
    countDownformate.value = 'HH:mm:ss';
  }
};

onLoad(async (query) => {
  complaintId.value = query?.id as string;
  await getDetails();
  await getOrderDetails();
  loading.value = false;
});

const refreshing = ref(false);
const refreshHandle = async () => {
  refreshing.value = true;
  await getDetails();
  await getOrderDetails();
  refreshing.value = false;
};

const isShowMessage = ref(false);
const cancelHandle = async () => {
  const result = await uni.showModal({
    title: '撤销投诉',
    content: '确定要撤销投诉吗？'
  });
  if (!result.confirm) return;
  uni.showLoading({ mask: true });
  const response = await $api.postOrderComplaintRevocationId(complaintId.value);
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '撤销成功', icon: 'none' });
      getDetails();
      break;
  }
};

const isShowFeedback = ref(false);
const handleFeedback = async (result: boolean) => {
  isShowFeedback.value = false;
  uni.showLoading({ mask: true });
  const response = await $api.postOrderComplaintFeedbackId(complaintId.value, {
    accept_flag: result
  });
  uni.hideLoading();
  switch (response.__error) {
    case undefined:
      uni.showToast({ title: '反馈成功', icon: 'none' });
      getDetails();
      break;
  }
};

const redirectToComplaint = () => {
  const pageStore = $store.page();
  pageStore.setParameters({ order: order.value });
  uni.redirectTo({ url: '/pages/complaint/complaint-type-select' });
};
</script>

<style lang="scss" scoped>
.dialog-list {
  .time {
    margin: 0 24rpx 24rpx;
    line-height: 32rpx;
    font-size: 24rpx;
    text-align: center;
    color: #999999;
  }
  .feedback-container {
    background-color: #ffffff;
    border-radius: 24rpx;
    padding: 36rpx 24rpx;
    margin: 0 24rpx 32rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 24rpx;
    .main {
      display: flex;
      align-items: center;
      gap: 16rpx;
      .main-text {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
      }
    }
    .sub {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #666666;
      .countdown {
        margin: 0 16rpx;
      }
      .complaint-button {
        color: #ff6d73;
      }
    }
  }
  .dialog-item {
    margin: 0 24rpx 24rpx;
    display: flex;
    align-items: flex-start;
    gap: 24rpx;
    &.user {
      justify-content: flex-end;
    }
    &.merchant {
      justify-content: flex-start;
    }
    .dialog-block {
      background-color: #ffffff;
      border-radius: 24rpx;
      padding: 24rpx;
      display: flex;
      align-items: stretch;
      flex-direction: column;
      gap: 12rpx;
      max-width: calc(100% - 216rpx);
      &.width-fix {
        width: calc(100% - 216rpx);
      }
      .dialog-block-item {
        display: flex;
        align-items: flex-start;
        line-height: 36rpx;
        gap: 12rpx;
        .label {
          flex-shrink: 0;
        }
        .content {
          flex: 1;
          min-width: 0;
          white-space: pre-wrap;
          word-break: break-all;
        }
        .image-list {
          flex: 1;
          min-width: none;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 12rpx;
        }
      }
    }
    .merchant-avatar,
    .user-avatar {
      width: 60rpx;
      height: 60rpx;
      line-height: 60rpx;
      text-align: center;
      font-size: 28rpx;
      border-radius: 30rpx;
      color: white;
      font-weight: bold;
      flex-shrink: 0;
    }
    .merchant-avatar {
      background: linear-gradient(180deg, #8d95f0 0%, #3647ff 100%);
    }
    .user-avatar {
      background: linear-gradient(161.57deg, #ff6f6f 28.44%, #ff2f3b 75.31%);
    }
  }
}
.details-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 100rpx;
  .finished-button {
    height: 80rpx;
    flex: 1;
    background-color: #f5f6fa;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16rpx;
    .finished-button-text {
      font-size: 28rpx;
    }
  }
}

.popper-container {
  width: 560rpx;
  box-sizing: border-box;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 50rpx;
  .popper-title {
    line-height: 60rpx;
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
  }
  .popper-content {
    font-size: 28rpx;
    color: #999999;
    text-align: center;
  }
  .popper-button-list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 24rpx;
  }
}
</style>
